# FILE: CustomerManager
# DESC: Manages collection of Customer objects
#

#import GeoOntologyManager

import MySQLdb

from infra.logging import logger
from infra.db import DBManager
from web.entity.Customer import Customer

class NoSuchCustomer(RuntimeError):
	pass


class CustomerManager:

	def createCustomer(self, name, url, isActive = True):
		# TODO: add exception handling
		rv = None
		cursor = self.dbMgr_.getCursor()
		cursor.execute("SELECT * from customer WHERE url = %s", (url))
		if cursor.rowcount > 0:
			row = cursor.fetchone()
			rv = Customer.Customer(row[0], row[1], row[2], row[3])
		else:
			cursor.execute("INSERT INTO customer (name, url, active) VALUES(%s, %s)", (name, url, isActive))
			cursor.execute("SELECT MAX(id) FROM customer")
			rv = Customer.Customer(cursor.fetchone()[0], name, url, isActive)
		return rv


	# return: list of customer objects if ok, empty list otherwise
	def getCustomers(self):
		log = logger.getLogger()
		customers = [] 
		cursor = DBManager.getCursor() 
		if cursor:
			try:
				log.debug("Fetching Customers records from database...") 
				cursor.execute("SELECT * from customer")
				log.debug("Customers records fetched.") 

				log.debug("Populating list of Customer objects...") 
				for customerRec in cursor.fetchall():
					customers.append(Customer(customerRec))
				log.info("List of %d Customer objects populated." % len(customers)) 
			except MySQLdb.Error, e:
				log.error("MySQLdb error %d: %s" % (e.args[0], e.args[1]))
		else:
			log.error("Failed to obtain database cursor!")
		return customers 


	# return: customer object if ok, throw an exception otherwise
	def getCustomer(self, customerId):
		customer = None
		try:
			log = logger.getLogger()
			cursor = DBManager.getCursor()
			log.debug("Fetching customer record with id = %s from database..." % customerId) 
			cursor.execute("SELECT * from customer where id = %s", customerId)
			log.debug("Customer record fetched.") 

			customerRec = cursor.fetchone()
			if customerRec:
				customer = Customer(customerRec)
			else:
				err = "Did not find customer record with id = %s." % customerId
				log.error(err)
				raise NoSuchCustomer(err)
			
			return customer
		
		except MySQLdb.Error, e:
			log.error("MySQLdb error %d: %s" % (e.args[0], e.args[1]))
			raise
